//
//  ProductEditViewController.m
//  DemoCoreData
//
//  Created by tangkexiong on 16/3/16.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "ProductEditViewController.h"

#import "CategoryChoiceViewController.h"

#import "YCCoreDataManager+CDProduct.h"

@interface ProductEditViewController()<CategoryChoiceVCDelegate> {
    YCProductCategory *_tempCategory;
}

@end

@implementation ProductEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (_product) {
        _nameTxtFld.text = _product.mName;
        _priceTxtFld.text = [NSString stringWithFormat:@"%.02lf", [_product.mPrice doubleValue]];
        _categoryLabel.text = _product.mCategory.mName;
        _categoryLabel.textColor = [UIColor blackColor];
        
        _tempCategory = _product.mCategory;
    }
}

#pragma mark - CategoryChoiceVCDelegate

- (void)categoryChoiceVC:(CategoryChoiceViewController *)vc didSelectCategory:(YCProductCategory *)category {
    [vc dismissViewControllerAnimated:YES completion:nil];
    
    _tempCategory = category;
    
    if (_tempCategory) {
        _categoryLabel.text = _tempCategory.mName;
        _categoryLabel.textColor = [UIColor blackColor];
    }
}

#pragma mark - IBAction

- (IBAction)choiceCategoryBtnClicked:(id)sender {
    CategoryChoiceViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"vcCategoryChoice"];
    vc.category = _tempCategory;
    vc.myDelegate = self;
    
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
    
    [self presentViewController:navi animated:YES completion:nil];
}

- (IBAction)doneBtnClicked:(id)sender {
    YCProduct *product = [[YCProduct alloc] init];
    
    product.mName = _nameTxtFld.text;
    product.mCategory = _tempCategory;
    product.mPrice = [[NSDecimalNumber alloc] initWithDouble:[_priceTxtFld.text doubleValue]];
    
    if (_product) {
        product.mId = _product.mId;
        
        [[YCCoreDataManager sharedInstance] updateProduct:product block:^(NSError *error, YCProduct *product) {
            if (error == nil) {
                if ([_myDelegate respondsToSelector:@selector(productEditVC:didEdit:isAdd:)]) {
                    [_myDelegate productEditVC:self didEdit:product isAdd:_product==nil];
                }
            }
        }];
    } else {
        [[YCCoreDataManager sharedInstance] insertProduct:product block:^(NSError *error, YCProduct *product) {
            if (error == nil) {
                if ([_myDelegate respondsToSelector:@selector(productEditVC:didEdit:isAdd:)]) {
                    [_myDelegate productEditVC:self didEdit:product isAdd:_product==nil];
                }
            }
        }];
    }
}

@end
